<template>
  <div class="service-detail-container">
    <div v-loading="loading">
      <el-card class="service-card" v-if="service.id">
        <div class="service-header">
          <h1 class="service-title">{{ service.name }}</h1>
          <el-tag type="success" v-if="service.status === 1">可预约</el-tag>
          <el-tag type="info" v-else>暂停预约</el-tag>
        </div>
        
        <div class="service-content">
          <div class="service-image" v-if="service.imageUrl">
            <img :src="getImageUrl(service.imageUrl)" alt="服务图片">
          </div>
          <div class="service-info">
            <div class="info-item">
              <span class="label">服务类别：</span>
              <span>{{ getCategoryText(service.category) }}</span>
            </div>
            <div class="info-item">
              <span class="label">服务价格：</span>
              <span class="price">¥{{ service.price }}</span>
            </div>
            <div class="info-item">
              <span class="label">服务时长：</span>
              <span>{{ service.duration }}分钟</span>
            </div>
            <div class="description-item">
              <div class="label">服务描述：</div>
              <div class="description">{{ service.description || '暂无描述' }}</div>
            </div>
          </div>
        </div>
        
        <div class="service-footer">
          <el-button 
            type="primary" 
            size="medium" 
            :disabled="service.status !== 1 || !isLoggedIn"
            @click="handleAppointment">
            立即预约
          </el-button>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </el-card>

      <!-- 预约表单 -->
      <el-dialog
        title="预约服务"
        :visible.sync="dialogVisible"
        width="500px"
        @close="resetForm">
        <el-form :model="form" :rules="rules" ref="appointmentForm" label-width="100px">
          <el-form-item label="服务名称">
            <span>{{ service.name }}</span>
          </el-form-item>
          <el-form-item label="服务价格">
            <span class="price">¥{{ service.price }}</span>
          </el-form-item>
          <el-form-item label="服务时长">
            <span>{{ service.duration }}分钟</span>
          </el-form-item>
          <el-form-item label="选择宠物" prop="petId">
            <el-select v-model="form.petId" placeholder="请选择宠物" style="width: 100%">
              <el-option
                v-for="pet in pets"
                :key="pet.id"
                :label="pet.name"
                :value="pet.id">
              </el-option>
            </el-select>
            <div v-if="!hasPets" class="no-pets-tip">
              您还没有添加宠物信息，请先 
              <router-link to="/main/pets/create">添加宠物</router-link>
            </div>
          </el-form-item>
          <el-form-item label="预约日期" prop="appointmentDate">
            <el-date-picker
              v-model="form.appointmentDate"
              type="date"
              placeholder="选择日期"
              :picker-options="datePickerOptions"
              style="width: 100%">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="预约时间" prop="appointmentTime">
            <el-time-select
              v-model="form.appointmentTime"
              :picker-options="{
                start: '09:00',
                step: '00:30',
                end: '18:00'
              }"
              placeholder="选择时间"
              style="width: 100%">
            </el-time-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              type="textarea"
              v-model="form.remark"
              placeholder="请输入备注信息"
              :rows="3">
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAppointment" :loading="submitting">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getServiceDetail } from '@/api/service'
import { getMyPets } from '@/api/pet'
import { createAppointment } from '@/api/service'
import { mapState } from 'vuex'

export default {
  name: 'ServiceDetail',
  data() {
    return {
      service: {},
      loading: false,
      submitting: false,
      dialogVisible: false,
      pets: [],
      form: {
        petId: '',
        appointmentDate: '',
        appointmentTime: '',
        remark: ''
      },
      rules: {
        petId: [
          { required: true, message: '请选择宠物', trigger: 'change' }
        ],
        appointmentDate: [
          { required: true, message: '请选择预约日期', trigger: 'change' }
        ],
        appointmentTime: [
          { required: true, message: '请选择预约时间', trigger: 'change' }
        ]
      },
      datePickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
        }
      }
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    serviceId() {
      return this.$route.params.id
    },
    isLoggedIn() {
      return !!this.userInfo
    },
    hasPets() {
      return this.pets.length > 0
    }
  },
  created() {
    this.fetchServiceDetail()
    if (this.isLoggedIn) {
      this.fetchMyPets()
    }
  },
  methods: {
    getImageUrl(path) {
      if (!path) return '';
      
      // 如果已经是完整的URL，直接返回
      if (path.startsWith('http://') || path.startsWith('https://')) {
        return path;
      }
      
      // 确保路径格式正确
      const cleanPath = path.startsWith('/') ? path : `/${path}`;
      
      // 返回完整的URL
      return `http://localhost:8080${cleanPath}`;
    },
    
    async fetchServiceDetail() {
      try {
        this.loading = true
        const response = await getServiceDetail(this.serviceId)
        
        if (response.code === 200) {
          this.service = response.data
        } else {
          this.$message.error(response.message || '获取服务详情失败')
        }
      } catch (error) {
        console.error('获取服务详情失败:', error)
        this.$message.error('获取服务详情失败')
      } finally {
        this.loading = false
      }
    },
    
    async fetchMyPets() {
      try {
        const response = await getMyPets()
        
        if (response.code === 200) {
          this.pets = response.data
        } else {
          this.$message.error(response.message || '获取宠物列表失败')
        }
      } catch (error) {
        console.error('获取宠物列表失败:', error)
        this.$message.error('获取宠物列表失败')
      }
    },
    
    getCategoryText(category) {
      const categoryMap = {
        'GROOMING': '美容服务',
        'HEALTH_CHECK': '健康检查',
        'VACCINATION': '疫苗接种',
        'BOARDING': '寄养服务',
        'TRAINING': '训练服务'
      }
      return categoryMap[category] || category
    },
    
    handleAppointment() {
      if (!this.isLoggedIn) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }
      
      if (!this.hasPets) {
        this.fetchMyPets()
      }
      
      this.dialogVisible = true
    },
    
    resetForm() {
      if (this.$refs.appointmentForm) {
        this.$refs.appointmentForm.resetFields()
      }
      
      this.form = {
        petId: '',
        appointmentDate: '',
        appointmentTime: '',
        remark: ''
      }
    },
    
    async submitAppointment() {
      this.$refs.appointmentForm.validate(async (valid) => {
        if (valid) {
          try {
            this.submitting = true
            
            // 组合日期和时间
            const date = this.form.appointmentDate
            const timeStr = this.form.appointmentTime
            
            if (!date || !timeStr) {
              this.$message.warning('请选择预约日期和时间')
              return
            }
            
            const [hours, minutes] = timeStr.split(':').map(Number)
            date.setHours(hours, minutes, 0, 0)
            
            const appointmentData = {
              serviceId: this.service.id,
              petId: this.form.petId,
              appointmentTime: date.toISOString(),
              remark: this.form.remark
            }
            
            const response = await createAppointment(appointmentData)
            
            if (response.code === 200) {
              this.$message.success('预约成功')
              this.dialogVisible = false
              this.$router.push('/main/my-appointments')
            } else {
              this.$message.error(response.message || '预约失败')
            }
          } catch (error) {
            console.error('预约失败:', error)
            this.$message.error('预约失败，请稍后再试')
          } finally {
            this.submitting = false
          }
        }
      })
    },
    
    goBack() {
      this.$router.push('/main/services')
    }
  }
}
</script>

<style lang="scss" scoped>
.service-detail-container {
  padding: 20px;
  
  .service-card {
    .service-header {
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      
      .service-title {
        margin: 0;
        margin-right: 15px;
        font-size: 24px;
        color: #303133;
      }
    }
    
    .service-content {
      margin-bottom: 30px;
      
      .service-image {
        margin-bottom: 20px;
        text-align: center;
        
        img {
          max-width: 400px;
          max-height: 500px;
          width: auto;
          height: auto;
          border-radius: 4px;
          object-fit: contain;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
      }
      
      .service-info {
        .info-item {
          margin-bottom: 15px;
          font-size: 15px;
          
          .label {
            font-weight: bold;
            color: #606266;
            margin-right: 10px;
          }
          
          .price {
            color: #f56c6c;
            font-weight: bold;
            font-size: 18px;
          }
        }
        
        .description-item {
          margin-top: 20px;
          
          .label {
            font-weight: bold;
            color: #606266;
            margin-bottom: 10px;
          }
          
          .description {
            padding: 15px;
            background-color: #f5f7fa;
            border-radius: 4px;
            line-height: 1.6;
            color: #606266;
            white-space: pre-wrap;
          }
        }
      }
    }
    
    .service-footer {
      border-top: 1px solid #ebeef5;
      padding-top: 20px;
      text-align: center;
    }
  }
  
  .no-pets-tip {
    margin-top: 5px;
    font-size: 12px;
    color: #e6a23c;
  }
  
  .price {
    color: #f56c6c;
    font-weight: bold;
  }
}
</style> 